package com.ya.jedis.protocol;

import com.ya.jedis.command.Command;

import java.io.IOException;
import java.io.OutputStream;

public class Protocol {

    private static final String STAR = "*";
    private static final String DOLLAR = "$";
    private static final String CRLF = "\r\n";

    public static void sendCommand(OutputStream outputStream, Command command, byte[]... args) {
        StringBuilder builder = new StringBuilder();
        // *3
        builder.append(STAR).append(args.length + 1).append(CRLF);
        // $3
        // SET
        builder.append(DOLLAR).append(command.name().length()).append(CRLF);
        builder.append(command.name()).append(CRLF);
        // $3
        // foo
        // $3
        // bar
        for (byte[] arg : args) {
            builder.append(DOLLAR).append(arg.length).append(CRLF);
            builder.append(new String(arg)).append(CRLF);
        }
        // System.out.println("write: \r\n"+builder);
        try {
            outputStream.write(builder.toString().getBytes());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
